package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.Comment;
import com.tanhua.model.db.FocusUser;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.db.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther : 白月尘
 * @date : 14:31  2021/10/25
 */
@Service
public class SmallVideosService {
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private FastFileStorageClient client;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private FocusUserApi focusUserApi;
    @Autowired
    private MqMessageService mqMessageService;
    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // @CacheEvict
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) {
        try {
            Video video = new Video();
            String fileName = videoFile.getOriginalFilename();
            fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
            StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                    videoFile.getSize(), fileName, null);
            String fullPath = storePath.getFullPath();
            String url = webServer.getWebServerUrl() + fullPath;
            String upload = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            video.setCreated(System.currentTimeMillis());
            video.setPicUrl(upload);
            video.setText("又是一年花开日");
            video.setUserId(UserHolder.getUserId());
            video.setVideoUrl(url);
            String id = videoApi.saveVideo(video);
            mqMessageService.sendLogService(UserHolder.getUserId(), "0301", "video", id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // @Cacheable(
    //         value="videos",
    //         key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    public PageResult findVideos(Integer page, Integer pageSize) {
        String key = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String s = redisTemplate.opsForValue().get(key);
        List<Video> list = new ArrayList<>();
        if (StringUtils.isEmpty(s)) {
            list = videoApi.findAll(page, pageSize);
        } else {
            String[] strings = s.split(",");
            list = videoApi.findByIds(strings, page, pageSize);
        }
        if (list == null || list.size() <= 0) {
            return new PageResult();
        }
        List<VideoVo> vos = new ArrayList<>();
        List<Long> ids = CollUtil.getFieldValues(list, "userId", long.class);
        Map<Long, UserInfo> map = userInfoApi.findAll(ids);
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            VideoVo vo = VideoVo.init(userInfo, video);
            vos.add(vo);
        }
        return new PageResult(page, pageSize, 0l, vos);
    }

    //视频用户关注
    public void saveFocusUser(long uid) {
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());
        focusUser.setFollowUserId(UserHolder.getUserId());
        focusUser.setUserId(uid);
        focusUserApi.saveFocusUser(focusUser);
    }

    public void deleteFocusUser(long uid) {
        focusUserApi.deleteFocusUser(uid, UserHolder.getUserId());
    }

    //视频点赞
    public void like(String id) {
        mqMessageService.sendLogService(UserHolder.getUserId(), "0302", "video", id);
    }

    //取消点赞
    public void disLike(String id) {
        mqMessageService.sendLogService(UserHolder.getUserId(), "0303", "video", id);
    }

    //评论列表
    public PageResult comments(Integer page, Integer pagesize, String id) {
        List<Comment> comment = commentApi.commentByVideo(page, pagesize, id);
        // System.out.println(comment);
        if (comment == null || comment.size() <= 0) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comment, "userId", Long.class);
        Map<Long, UserInfo> all = userInfoApi.findAll(userIds);

        List<CommentVo> commentVos = new ArrayList<>();
        for (Comment comment1 : comment) {
            UserInfo userInfo = all.get(comment1.getUserId());
            CommentVo vo = CommentVo.init(userInfo, comment1);
            commentVos.add(vo);
        }
        // System.out.println(commentVos);
        return new PageResult(page, pagesize, 0L, commentVos);

    }

    //发布评论
    public ResponseEntity saveComments(String content, String id) {
        //1.补全Comment对象数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(2);
        comment.setUserId(UserHolder.getUserId());
        comment.setContent(content);
        comment.setCreated(System.currentTimeMillis());

        //设置被评论的用户
        Video video = videoApi.findById(id);
        comment.setPublishUserId(video.getUserId());
        // System.out.println(comment);
        //保存评论对象数据
        commentApi.saveComments(comment);


        return ResponseEntity.ok(null);
    }
}
